﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cesave.Domain.PermisosModule.Entities;
using System.ComponentModel;
using Cesave.Application.Permisos.ServiceAgent;
using System.Windows.Forms;

namespace Cesave.Presentation.Permisos.WinForms.Client.ViewModels.Permisos
{
	public partial class ExpedicionViewModel
	{
		#region Private properties

		/// <summary>
		/// 
		/// </summary>
		private List<Area> _areas;

		/// <summary>
		/// 
		/// </summary>
		private Area _area;

		#endregion

		#region Public properties

		/// <summary>
		/// 
		/// </summary>
		public List<Area> Areas
		{
			get
			{
				return _areas;
			}
			private set
			{
				_areas = value;
				if (_areas != null)
					RaisePropertyChanged("Areas");
			}
		}
		
		/// <summary>
		/// 
		/// </summary>
		public Area Area
		{
			get
			{
				return _area;
			}
			private set
			{
				_area = value;
				if (_area != null)
					RaisePropertyChanged("Area");
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public bool IsAreaReady
		{
			get
			{
				return Area != null;
			}
		}

		#endregion

		#region Private methods

		/// <summary>
		/// 
		/// </summary>
		private void LoadAreas()
		{
			StartWaiting();
			using (BackgroundWorker worker = new BackgroundWorker())
			{
				worker.DoWork += (sender, e) =>
				{
					using (PermisosModuleServiceWrapper service = new PermisosModuleServiceWrapper())
					{
						e.Result = service.FindAreasByJuntaArea(_pusSettings.Junta.JuntaGuid);
					}
				};
				worker.RunWorkerCompleted += (sender, e) =>
				{
					EndWaiting();
					if (!e.Cancelled && e.Error == null)
						Areas = e.Result as List<Area>;
					else if (e.Error != null)
						ShowMessage(e.Error.Message);
				};
				worker.WorkerSupportsCancellation = true;
				worker.RunWorkerAsync();
			}
		}

		#endregion

		#region Event methods

		/// <summary>
		/// 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void SetCurrentArea(object sender, EventArgs e)
		{
			BindingSource bindingSource = sender as BindingSource;
			if (bindingSource != null)
				if (bindingSource.Current != null)
					Area = bindingSource.Current as Area;
		}

		/// <summary>
		/// 
		/// </summary>
		private void OnAreasPropertyChanged()
		{
			_expedicionView.areasBindingSource.DataSource = Areas;
			_expedicionView.areasBindingSource.CurrentChanged += SetCurrentArea;
			SetCurrentArea(_expedicionView.areasBindingSource, new EventArgs());
		}

		/// <summary>
		/// 
		/// </summary>
		private void OnAreaPropertyChanged()
		{
			LoadFoliosPermiso();
		}

		#endregion
	}
}